package com.yimi.yinhepda.views.createPackage_module;

import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

import butterknife.Bind;

import com.yimi.yinhepda.R;
import com.yimi.yinhepda.adapter.DeleteByHandAdapter;
import com.yimi.yinhepda.db.dao.BuildPckScanTableDao;
import com.yimi.yinhepda.entity.bean.DeleteEntity;
import com.yimi.yinhepda.entity.response.BuildPackageDetailResponse;
import com.yimi.yinhepda.event.CountEvent;
import com.yimi.yinhepda.utils.IntentUtils;
import com.pda.ym.utils.SoundVibratorManager;
import com.pda.ym.utils.StringUtils;
import com.yimi.yinhepda.base.BaseInitActivity;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.greenrobot.eventbus.EventBus;

/**
 * @author 000432
 * @date 2017/4/10 0010
 * <p>
 * 手动撤销
 */
public class CreateDeleteByHandActivity extends BaseInitActivity {

    /**
     * 标题栏左边
     */
    @Bind(R.id.title)
    TextView mTvTitle;
    /**
     * 标题栏中间
     */
    @Bind(R.id.num)
    TextView mTvNum;
    /**
     * 添加按钮
     */
    @Bind(R.id.manual_delete_btn)
    Button mBtnDelete;
    /**
     * 条码输入框
     */
    @Bind(R.id.load_addchildwaybill_ed)
    EditText mEtBarcode;
    @Bind(R.id.add_chidlwaybill_listview)
    ListView mListView;
    @Bind(R.id.manaul_delete_count)
    TextView mTvDeleteTip;
    @Bind(R.id.add_childwaybill_ok)
    Button mImgAddOk;

    private BuildPckScanTableDao mBuildPckScanTableDao;
    private List<DeleteEntity> mDeleteEntityList = new ArrayList<>();
    private DeleteByHandAdapter mAdapter;
    /**
     * 手加票
     */
    private int mHandDeleteBill;
    /**
     * 手加件
     */
    private int mHandDeleteItem;
    /**
     * 建包目的地
     */
    private String destCode;
    private String destName;
    /**
     * 总的未上传数量
     */
    private int totalNotUploadNum;
    /**
     * 任务号
     */
    private String taskNo;

    private List<BuildPackageDetailResponse.StockInfo> buildList;

    @Override
    public String getPageName() {
        return getString(R.string.page_create_addbydelete);
    }

    public CreateDeleteByHandActivity() {
        super(true);
    }

    @Override
    protected void handleBarCode(String result) {
        super.handleBarCode(result);
        if (result == null) {
            SoundVibratorManager.playSound(2);
            showToast("运单号扫描失败");
        } else {
            mEtBarcode.setText(result);
            startDeleteBarData();
        }
    }

    @Override
    public int getContentViewId() {
        return R.layout.activity_delete_childbillway;
    }

    @Override
    public void initView(Bundle savedInstanceState) {
        mTvTitle.setText(getString(R.string.hand_delete_title));
    }

    @Override
    public void initEvent() {
        mBtnDelete.setOnClickListener(this);
        mImgAddOk.setOnClickListener(this);
    }

    @Override
    public void initData() {
        //目的地
        destCode = getIntent().getStringExtra(IntentUtils.BUILD_DEST);
        destName = getIntent().getStringExtra(IntentUtils.BUILD_DEST_NAME);
        taskNo = getIntent().getStringExtra(IntentUtils.BUILD_PKG_TASK_NO);
        buildList = CreatePackageScanActivity.buildList;
        //数据库对象
        mBuildPckScanTableDao = new BuildPckScanTableDao();
        totalNotUploadNum = mBuildPckScanTableDao.queryNotUploadDataNum(taskNo);
        mTvNum.setText(totalNotUploadNum + "");

        //列表
        mAdapter = new DeleteByHandAdapter(this, mDeleteEntityList);
        mListView.setAdapter(mAdapter);
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);

        switch (v.getId()) {
            case R.id.manual_delete_btn:
                //撤销按钮
                startDeleteBarData();
                break;
            case R.id.add_childwaybill_ok:
                //确定按钮
                activityBackMethod();
                break;
            default:
                break;
        }
    }

    /**
     * 开始添加条码的操作
     */
    private void startDeleteBarData() {

        String barCodeStr = mEtBarcode.getText().toString().trim();

        Boolean isMasterWaybillNo = StringUtils.isMasterWayBillNo(barCodeStr);

        //判断单号长度
        if (!StringUtils.isWaybillNo(barCodeStr) && !isMasterWaybillNo) {
            SoundVibratorManager.playSound(2);
            showToast("运单号不规范");
            return;
        }

        if (isMasterWaybillNo) {
            //撤销主单号
            for (BuildPackageDetailResponse.StockInfo stockInfo : buildList) {
                if (stockInfo.getWaybillNo().equals(barCodeStr)) {
                    boolean hasFlag = false;
                    List<BuildPackageDetailResponse.ChildInfo> childList = stockInfo.getChildList();
                    int count = 0;
                    for (BuildPackageDetailResponse.ChildInfo child : childList) {
                        if (child.getFlag() == 1) {
                            count++;
                            child.setFlag(0);
                            hasFlag = true;
                            /** 从表中删除扫描数据*/
                            if (deleteScannedData(child) < 0) {
                                SoundVibratorManager.playSound(2);
                                showToast("插入数据库失败!");
                                return;
                            }
                            totalNotUploadNum--;
                        }
                    }
                    if (!hasFlag) {
                        SoundVibratorManager.playSound(2);
                        showToast("该条码还未扫描!");
                        return;
                    }
                    mTvNum.setText(totalNotUploadNum + "");
                    EventBus.getDefault().post(new CountEvent(totalNotUploadNum));
                    SoundVibratorManager.playSound(1);
                    /** 查询数据库中当前运单下的已经扫描的数量*/
                    int scannedNum = mBuildPckScanTableDao.getScannedDataList(stockInfo.getWaybillNo());
                    boolean isChanged = false;
                    /** 列表中已经有对应运单号的撤销，加一个就好，如果没有加新的一行*/
                    if (mDeleteEntityList != null) {
                        for (int j = 0; j < mDeleteEntityList.size(); j++) {
                            DeleteEntity deleteEntity = mDeleteEntityList.get(j);
                            if (deleteEntity.getWayBillNo().equals(stockInfo.getWaybillNo())) {
                                deleteEntity.setScannedNum(scannedNum);
                                deleteEntity.setDeleteNum(count + deleteEntity.getDeleteNum());
                                mAdapter.notifyDataSetChanged();
                                isChanged = true;
                                break;
                            }
                        }
                    }
                    /***
                     * 之前没有撤销过的单子，自己添加一行到列表
                     */
                    if (!isChanged) {
                        DeleteEntity deleteEntity = new DeleteEntity();
                        deleteEntity.setWayBillNo(stockInfo.getWaybillNo());
                        deleteEntity.setScannedNum(scannedNum);
                        deleteEntity.setDeleteNum(count);
                        mDeleteEntityList.add(deleteEntity);
                        mAdapter.notifyDataSetChanged();
                    }

                    /** 刷新手动撤销的票和件*/
                    mHandDeleteBill = getHandDeleteBill();
                    int deleteCount = getHandDeleteBillNum();
                    mTvDeleteTip.setText(String.format(getString(R.string.hand_delete_num), mHandDeleteBill, deleteCount));
                    return;
                }
            }
        } else {
            /***
             * 撤销子单号
             * buildList 是扫描页面全局的
             */
            boolean hasWaybillNo = false;
            for (int i = 0; i < buildList.size(); i++) {

                //当前行的运单信息，包括子单的集合
                BuildPackageDetailResponse.StockInfo currentItemInfo = buildList.get(i);
                /** 判断子单是不是以主单开始的,减少循环次数*/
                if (!barCodeStr.startsWith(String.valueOf(currentItemInfo.getWaybillNo()))) {
                    continue;
                }
                hasWaybillNo = true;
                //子单的集合
                List<BuildPackageDetailResponse.ChildInfo> childList = currentItemInfo.getChildList();
                //循环子单的集合
                for (BuildPackageDetailResponse.ChildInfo child : childList) {
                    //子单字符串
                    String childWaybillno = child.getChildWaybillNo();
                    //扫描子单和集合中一个子单相同
                    if (barCodeStr.equals(childWaybillno)) {
                        Integer flag = child.getFlag();

                        if (flag == 0) {
                            SoundVibratorManager.playSound(2);
                            showToast("该条码还未扫描!");
                        } else if (flag == 1) {
                            /** 从表中删除扫描数据*/
                            if (deleteScannedData(child) < 0) {
                                SoundVibratorManager.playSound(2);
                                showToast("插入数据库失败!");
                                return;
                            }

                            totalNotUploadNum--;
                            mTvNum.setText(totalNotUploadNum + "");
                            EventBus.getDefault().post(new CountEvent(totalNotUploadNum));

                            SoundVibratorManager.playSound(1);
                            /** 为未扫描的状态*/
                            child.setFlag(0);

                            /** 查询数据库中当前运单下的已经扫描的数量*/
                            int scannedNum = mBuildPckScanTableDao.getScannedDataList(currentItemInfo.getWaybillNo());

                            boolean isChanged = false;
                            /** 列表中已经有对应运单号的撤销，加一个就好，如果没有加新的一行*/
                            if (mDeleteEntityList != null) {
                                for (int j = 0; j < mDeleteEntityList.size(); j++) {
                                    DeleteEntity deleteEntity = mDeleteEntityList.get(j);
                                    //扫描的子单对应运单号在列表已经有了，撤销数量加1就好
                                    if (deleteEntity.getWayBillNo().equals(currentItemInfo.getWaybillNo())) {
                                        deleteEntity.setDeleteNum(deleteEntity.getDeleteNum() + 1);
                                        deleteEntity.setScannedNum(scannedNum);
                                        mAdapter.notifyDataSetChanged();
                                        isChanged = true;
                                        break;
                                    }
                                }
                            }
                            /***
                             * 之前没有撤销过的单子，自己添加一行到列表
                             */
                            if (!isChanged) {
                                DeleteEntity deleteEntity = new DeleteEntity();
                                deleteEntity.setWayBillNo(currentItemInfo.getWaybillNo());
                                deleteEntity.setScannedNum(scannedNum);
                                deleteEntity.setDeleteNum(1);
                                mDeleteEntityList.add(deleteEntity);
                                mAdapter.notifyDataSetChanged();
                            }

                            /** 刷新手动撤销的票和件*/
                            mHandDeleteBill = getHandDeleteBill();
                            int deleteCount = getHandDeleteBillNum();
                            mTvDeleteTip.setText(String.format(getString(R.string.hand_delete_num), mHandDeleteBill, deleteCount));
                        }

                        /** 更新当前行到第一行*/
                        buildList.remove(i);
                        buildList.add(0, currentItemInfo);
                        return;
                    }
                }
            }
            if (!hasWaybillNo) {
                SoundVibratorManager.playSound(2);
                showToast("该条码不存在列表中！");
            }
        }
    }

    /**
     * 手动添加的票数
     */
    private int getHandDeleteBill() {
        Set<String> set = new HashSet<String>();
        for (DeleteEntity item : mDeleteEntityList) {
            set.add(item.getWayBillNo());
        }
        return set.size();
    }

    /**
     * 手动撤销的件数
     */
    private int getHandDeleteBillNum() {
        int count = 0;
        for (DeleteEntity item : mDeleteEntityList) {
            count += item.getDeleteNum();
        }
        return count;
    }

    /**
     * 删除已经扫描的数据到表中
     *
     * @param child 当前子单的相关信息
     */
    private int deleteScannedData(BuildPackageDetailResponse.ChildInfo child) {
        int result = 0;
        try {
            result = mBuildPckScanTableDao.delelteByTaskNoAndChildBill(taskNo, child.getChildWaybillNo());
            Log.d("tag", "deleteScannedData: result=" + result);
        } catch (Exception e) {
            e.printStackTrace();
            result = -1;
        }
        return result;
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    private void activityBackMethod() {
        finish();
    }
}
